﻿using System.Linq;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Presentation.Events;
using Might.Infrastructure.Annotations.Graphics;
using Might.Infrastructure.DOM;
using Might.Infrastructure.Events;
using Might.Infrastructure.Services;
using Might.Modelica.Annotations.Graphics;

namespace Might.UIControls.ObjectBrowser {
    public class ObjectBrowserPresenter {
        public ObjectBrowserPresenter(IObjectBrowserView view) {
            View = view;
            View.ObjectSelected += ViewObjectDoubleClick;
            CoreServices.EventAggregator.GetEvent<PackageBrowserItemOpenEvent>().Subscribe(
                PackageBrowserItemOpenEventHandler, ThreadOption.UIThread, false);
        }
        
        public IObjectBrowserView View { get; set; }

        public void PackageBrowserItemOpenEventHandler(IDomNode node) {
            View.Clear();

            IDomNode anot = node.GetFirstChild(GroupNames.Annotations);
            if (anot == null) {
                return;
            }
            Icon icon = anot.GetFirstChild(GroupNames.Icons) as Icon;

            if (icon == null) {
                return;
            }
            foreach (IGraphicsItem item in icon.Children) {
                ListBoxItem listBoxItem = new ListBoxItem {Tag = item, Content = item.ToString().Split('.').Last()};
                View.AddItem(listBoxItem);
            }
        }

        private static void ViewObjectDoubleClick(object selectedItem) {
            if (selectedItem is IGraphicsItem) {
                (selectedItem as IGraphicsItem).Select();
            }
        }
    }
}
